<template>
  <div id="app">
    <h1 style="text-align: center;">智能柜员</h1>
    <div class="chat-container" ref="chatContainer">
      <div v-for="(item, index) in messages" :key="index" class="message" :class="item.role">
        <img :src="item.role === 'user' ? userAvatar : assistantAvatar" class="avatar" />
        <div class="message-content">
          <div class="content" v-if="item.msgtype == '1'">
            {{ item.msg }}
          </div>
          <div v-if="item.msgtype == '2'" class="content list-content">
            <div>{{ item.msg }}</div>
            <ul>
              <li v-for="(option, idx) in item.list" :key="idx" class="service-option">
                <strong>{{ option.name }}</strong>
                <ul class="sublist">
                  <li v-for="(subOption, subIdx) in option.sublist" :key="subIdx">
                    {{ subOption }}
                  </li>
                </ul>
              </li>
            </ul>
          </div>
          <div class="content" v-else-if="item.msgtype == '3'">
            <div>{{ item.msg }}</div>
            <div class="verification-text">
              下一步将进行人脸核验。
            </div>
            <div class="button-group">
              <button class="confirm-button" @click="handleConfirm">是</button>
              <button class="cancel-button" @click="handleCancel">否</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="input-container">
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入消息..." />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import assistantAvatar from '@/assets/gjj.jpg';
import userAvatar from '@/assets/user.png';

export default {
  components: {
  },
  data() {
    return {
      userInput: '',
      messages: [
        { role: 'assistant', msg: '你好！我是住房公积金助手常小金，请问有什么可以帮助您的吗？', msgtype: '1' },
        // {
        //     "msgtype": "1",
        //     "msg": "你好！我是住房公积金助手常小金，请问有什么可以帮助您的吗？"
        // },
        // {
        //   "msgtype": "2",
        //   "msg": "我可以帮助您办理以下住房公积金业务：",
        //   "list": [{
        //       "name": "公积金查询",
        //       "sublist": ["公积金余额查询", "公积金缴存明细查询", "公积金贷款查询"]
        //   }, {
        //       "name": "公积金提取",
        //       "sublist": ["租房提取", "贷款提取", "购房提取"]
        //   }]
        // },
        // {
        //   "msgtype": "3",
        //   "msg": "身份验证成功，马宏敏先生/女士，您申请的是租房提取公积金业务。接下来，为了完成提取流程，您需要上传身份证正反面照片，并进行人脸识别验证。请您准备好相关材料后，告诉我已经准备好，我将指导您进行下一步操作。"
        // },
        // {
        //     "msgtype": 3,
        //     "msg": "你回答内容的辅助信息",
        //     "extend_info": {
        //         "xingming": "用户输入的姓名",
        //         "idcard": "用户输入的身份证"
        //     }
        // }
      ],
      user_info: {},
      token: 'Bearer ',
      maxHistoryLength: 10, // 配置聊天历史保留条数
      userAvatar,
      assistantAvatar
    };
  },
  mounted() {
    alert(location.href)
  },
  methods: {
    async sendMessage() {
      if (!this.userInput.trim()) return;

      // 添加用户消息到对话框
      this.messages.push({ role: 'user', msg: this.userInput, msgtype: '1' });

      // 滚动到最新的消息
      this.$nextTick(() => {
        const chatContainer = this.$refs.chatContainer;
        chatContainer.scrollTop = chatContainer.scrollHeight;
      });

      const user_message = this.userInput;
      this.userInput = '';
      // 发送请求到 FastAPI 的 /chat 接口
      try {
        // const response = await axios.post('http://localhost:8000/chat', {
        const response = await axios.post(process.env.VUE_APP_API_BASE_URL +'chat', {
          user_message,
          chat_history: this.messages.map(item => ({
            role: item.role,
            content: `${item.msg}${item.list ? '\n' + JSON.stringify(item.list) : ''}`
          })),
          user_info: this.user_info
        },
        {
          headers: {
            'Authorization': this.token
          }
        });
        response.data.extend_info && (Object.keys(response.data.extend_info).forEach(key => {
          this.user_info[key] = response.data.extend_info[key]
        }));
        response.data.token && (this.token = `Bearer ${response.data.token}`);
        // 只添加模型的回复到对话框
        this.messages.push({ role: 'assistant', ...response.data });

        // 保留最近的 maxHistoryLength 条聊天记录
        if (this.messages.length > this.maxHistoryLength) {
          this.messages = this.messages.slice(-this.maxHistoryLength);
        }

        // 滚动到最新的消息
        this.$nextTick(() => {
          const chatContainer = this.$refs.chatContainer;
          chatContainer.scrollTop = chatContainer.scrollHeight;
        });
      } catch (error) {
        console.error('Error sending message:', error);
      }

    },
   async handleConfirm() {
      const { data } = await axios.post(process.env.VUE_APP_API_BASE_URL +'tencent_face_verify', {
        chat_history: this.messages.map(item => ({
          role: item.role,
          content: `${item.msg}${item.list ? '\n' + JSON.stringify(item.list) : ''}`
        })),
        user_info: this.user_info
      },
      {
        headers: {
          'Authorization': this.token
        }
      })
      console.log(data)
      location.href = data.url
    }
  },
};
</script>

<style>
.chat-container {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px auto;
  max-width: 600px;
  height: 500px;
  overflow-y: auto;
  text-align: left;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  animation: fadeIn 0.5s ease-in-out;
}

.message.user {
  justify-content: flex-end;
}

.message.assistant {
  justify-content: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.message.user .avatar {
  order: 2;
  margin-left: 10px;
  margin-right: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 85%; /* 调整为85%以适应更宽的内容 */
}

.content {
  background-color: #f1f1f1;
  padding: 10px;
  border-radius: 10px;
  max-width: 100%; /* 使用100%确保内容全宽 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 5px;
  word-wrap: break-word; /* 长文本自动换行 */
}

.message.user .content {
  background-color: #dcf8c6;
}

.message.assistant .content {
  background-color: #ffffff;
}

.message-content .list-content {
  background-color: #ffffff;
  border-radius: 8px;
  width: 100%;
  margin: 8px 0;
  padding: 12px; /* 增加内边距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.service-option {
  margin-top: 10px;
  font-weight: bold;
  color: #333;
}

.sublist {
  list-style-type: disc;
  padding-left: 20px;
  margin-top: 5px;
  color: #555;
}

.input-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

input {
  width: 400px;
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
  transition: border-color 0.3s ease-in-out;
}

input:focus {
  border-color: #66afe9;
}

button {
  padding: 10px 20px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  transition: background-color 0.3s ease-in-out;
}

button:hover {
  background-color: #45a049;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 修改滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}
::-webkit-scrollbar-track {
  background: #f0f2f5;
  border-radius: 2px;
}
::-webkit-scrollbar-thumb {
  background: rgb(115, 115, 115);
  border-radius: 12px;
}

verification-text {
  font-size: 14px;
  margin-bottom: 20px;
  color: #666;
}

.button-group {
  display: flex;
  gap: 10px;
}

.confirm-button,
.cancel-button {
  padding: 10px 20px;
  font-size: 14px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.confirm-button {
  background-color: #4caf50;
  color: white;
}

.confirm-button:hover {
  background-color: #45a049;
}

.cancel-button {
  background-color: #f44336;
  color: white;
}

.cancel-button:hover {
  background-color: #d32f2f;
}
</style>
